#include "includes.h"



static unsigned char cur_stat;
static unsigned char cur_sn;
static unsigned char cur_task;
static struct sockaddr cur_addr;
static PS_TASK_BUFF pstBuff;


int updata_sys_stat(PS_PACKET_DATA pst, struct sockaddr *pstAddr) 
{								
	cur_sn = pst->sn; 			
	cur_task = pst->content; 	
	//cur_stat = STAT_SYS_BUSY;
	memcpy(&cur_addr, pstAddr, sizeof(struct sockaddr));
	return 0;
}

int task_buff_init()
{
	pstBuff = Malloc(sizeof(S_TASK_BUFF));
	Pthread_mutex_init(&pstBuff->mutex, NULL);
	Pthread_cond_init(&pstBuff->cond, NULL);
	pstBuff->buff_len = 0;
	return 0;
}

int task_buff_write(char *data, int data_len)
{
	int len;
	len = min(data_len, TASK_BUFF_SIZE);
	Pthread_mutex_lock(&pstBuff->mutex);
	memcpy(pstBuff->buff, data, len);
	pstBuff->buff_len = len;
	Pthread_cond_signal(&pstBuff->cond);
	Pthread_mutex_unlock(&pstBuff->mutex);
	return 0;
}

int task_buff_read(char *buff, int buff_len)
{
	int len;
	Pthread_mutex_lock(&pstBuff->mutex);
	while(pstBuff->buff_len == 0)
	{
		Pthread_cond_wait(&pstBuff->cond, &pstBuff->mutex);
	}
	len = min(buff_len, pstBuff->buff_len);
	memcpy(buff, pstBuff->buff, len);
	pstBuff->buff_len = 0;
	Pthread_mutex_unlock(&pstBuff->mutex);
	return len;
}

int task_buff_read_timeout(char *buff, int buff_len, int time_out)
{
	int len;
	struct timespec to;
	Pthread_mutex_lock(&pstBuff->mutex);
	while(pstBuff->buff_len == 0)
	{
		to.tv_sec = time(NULL)+time_out;
		to.tv_nsec = 0;
		if (Pthread_cond_timedwait(&pstBuff->cond, &pstBuff->mutex, &to) != 0)
		{
			Pthread_mutex_unlock(&pstBuff->mutex);
			return -1;
		}
	}
	len = min(buff_len, pstBuff->buff_len);
	memcpy(buff, pstBuff->buff, len);
	pstBuff->buff_len = 0;
	Pthread_mutex_unlock(&pstBuff->mutex);
	return len;
}

unsigned char get_sys_stat()
{
	return cur_stat;
}

void set_sys_stat(unsigned char stat)
{
	cur_stat = stat;
	switch(stat)
	{
		case STAT_SYS_BUSY:
			printf("************system status: STAT_SYS_BUSY***************\n");
			break;
		case STAT_SYS_FREE:
			printf("************system status: STAT_SYS_FREE***************\n");
			break;
		case STAT_SYS_MIDDLE:
			printf("************system status: STAT_SYS_MIDDLE*************\n");
			break;			
		default:
			printf("************system status: unknow**********************\n");
			break;
	}
}

unsigned char get_cur_sn()
{
	return cur_sn;
}

unsigned char get_cur_task()
{
	return cur_stat;
}

struct sockaddr *get_cur_addr()
{
	return &cur_addr;
}
